package com.bz.match;

import com.bz.match.exception.MatchException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Component;

/**
 * Created on 2021/3/10
 *
 * @author zhongyongbin
 */
@Component
public class MatchMessagePublisher {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Qualifier("matchTopic")
    @Autowired
    private ChannelTopic matchTopic;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发布匹配消息
     *
     * @param gameId      游戏标识
     * @param playerCount 游戏人数
     * @throws MatchException 匹配异常
     */
    public void publish(int gameId, int playerCount) throws MatchException {
        try {
            String message = objectMapper.writeValueAsString(new MatchMessage(gameId, playerCount));
            redisTemplate.convertAndSend(matchTopic.getTopic(), message);
        } catch (Exception e) {
            throw new MatchException("Publish match message fail.", e);
        }
    }
}
